package main

import (
	"bytes"
	"encoding/json"
	"flag"
	"fmt"
	"io"
	"net/http"
	"os"
)

var url = "http://localhost:5656/animal"

//Animal 动物
type Animal struct {
	Id     int    `json:"Id"  xorm:"int64 pk 'Id'" form:"Id" binding:"required"` // Id
	Name   string `json:"name"  xorm:"varchar(20) notnull 'Name'" form:"Name"`   // 名字
	Age    int    `json:"age"  xorm:"int null 'Age'" form:"Age"`                 // 年龄
	Sex    int    `json:"sex"  xorm:"int null 'sex'" form:"Sex"`                 // 性别
	Weight int    `json:"weight"  xorm:"int null 'Weight'" form:"Weight"`        // 体重
}

func main() {
	fmt.Println("command add del update query")
	if len(os.Args) < 2 {
		fmt.Println("not enough param")
		return
	}
	data := Animal{}
	if len(os.Args) > 2 {
		cmd := flag.NewFlagSet("aa", flag.ExitOnError)
		cmd.IntVar(&data.Id, "id", 0, "animal id")
		cmd.StringVar(&data.Name, "n", "", "animal name")
		cmd.IntVar(&data.Age, "a", 0, "animal age")
		cmd.IntVar(&data.Weight, "w", 0, "animal weight")
		cmd.IntVar(&data.Sex, "s", 0, "animal sex  1 or 2")
		cmd.Usage()
		cmd.Parse(os.Args[2:])
	}

	strType := os.Args[1]
	switch strType {
	case "add":
		addAnimal(&data)
	case "del":
		delAnimal(&data)
	case "update":
		updateAnimal(&data)
	case "query":
		queryAnimal(&data)
	}
}

func addAnimal(data *Animal) {
	buf, _ := json.MarshalIndent(data, "", "  ")
	rd := bytes.NewBuffer(buf)
	rsp, err := http.Post(url, "application/json", rd)
	if err != nil {
		fmt.Println(err)
		return
	}
	printRsp(rsp)
}

func delAnimal(data *Animal) {
	if data.Id <= 0 {
		fmt.Println("need id param")
		return
	}
	newUri := fmt.Sprintf("%v?Id=%v", url, data.Id)
	r, err := http.NewRequest(http.MethodDelete, newUri, nil)
	if err != nil {
		return
	}
	//r.Header.Set("Content-Type", "application/json")
	rsp, err2 := http.DefaultClient.Do(r)
	if err2 != nil {
		return
	}
	printRsp(rsp)
}

func updateAnimal(data *Animal) {
	buf, _ := json.MarshalIndent(data, "", "  ")
	rd := bytes.NewBuffer(buf)
	r, err := http.NewRequest(http.MethodPut, url, rd)
	if err != nil {
		return
	}
	r.Header.Set("Content-Type", "application/json")
	rsp, err2 := http.DefaultClient.Do(r)
	if err != nil {
		fmt.Println(err2)
		return
	}
	printRsp(rsp)
}

func queryAnimal(data *Animal) {
	uri := fmt.Sprintf("%v?Id=%d", url, data.Id)
	rsp, err := http.Get(uri)
	if err != nil {
		fmt.Println(err)
		return
	}
	printRsp(rsp)
}

func printRsp(rsp *http.Response) {
	rspBuf, err3 := io.ReadAll(rsp.Body)
	if err3 != nil {
		fmt.Println(err3)
		return
	}
	fmt.Println(string(rspBuf))
	if len(rspBuf) > 0 {
		fmt.Println("--------------json---------------")
		b := bytes.Buffer{}
		err := json.Indent(&b, rspBuf, "", "  ")
		if err == nil {
			fmt.Println(string(b.Bytes()))
		}
	}
}